package org.ala.tiktools.rpc.tcp.config;

import io.netty.util.NettyRuntime;
import org.ala.tiktools.rpc.config.RpcConfigInfoParse;
import org.springframework.core.env.Environment;

/**
 * @author ala
 * @date 2025-04-04 13:28
 */
public class RpcTcpConfigInfoParser extends RpcConfigInfoParse {
    /**
     *  前缀
     */
    public static final String PREFIX = "ala-rpc.tcp";


    /**
     *  配置解析
     */
    public RpcTcpConfigInfo parseTcp(Environment env) {
        RpcTcpConfigInfo info = new RpcTcpConfigInfo();
        //  连接相关
        info.setPort(env.getProperty(PREFIX + ".port", Integer.class, 51001));
        info.setConnectionTimeoutMills(env.getProperty(PREFIX + ".connection_timeout_mills", Integer.class, 30000));
        info.setSoBacklog(env.getProperty(PREFIX + ".so_backlog", Integer.class, 50));
        info.setClientWorkerCount(env.getProperty(PREFIX + ".clientWorkerCount", Integer.class, -1));
        if (info.getClientWorkerCount() == -1) {
            info.setClientWorkerCount(NettyRuntime.availableProcessors() * 2);
        }
        info.setServerBossCount(env.getProperty(PREFIX + ".serverBossCount", Integer.class, -1));
        if (info.getServerBossCount() == -1) {
            info.setServerBossCount(1);
        }
        info.setServerWorkerCount(env.getProperty(PREFIX + ".serverWorkerCount", Integer.class, -1));
        if (info.getServerWorkerCount() == -1) {
            info.setServerWorkerCount(NettyRuntime.availableProcessors() * 2);
        }
        //  缓冲区相关
        info.setSoSndbuf(env.getProperty(PREFIX + ".so_sndbuf", Integer.class, 65536));
        info.setSoRcvbuf(env.getProperty(PREFIX + ".so_rcvbuf", Integer.class, 32768));
        info.setSoWriteBufferHighWaterMark(env.getProperty(PREFIX + ".so_write_buffer_high_water_mark", Integer.class, 65536));
        info.setSoWriteBufferLowWaterMark(env.getProperty(PREFIX + ".so_write_buffer_low_water_mark", Integer.class, 32768));
        //  tcp相关
        info.setSoKeepalive(env.getProperty(PREFIX + ".so_keepalive", Boolean.class, false));
        info.setTcpNoDelay(env.getProperty(PREFIX + ".tcp_nodelay", Boolean.class, false));
        info.setSoLinger(env.getProperty(PREFIX + ".so_linger", Integer.class, -1));
        //  读写控制相关
        info.setAutoRead(env.getProperty(PREFIX + ".auto_read", Boolean.class, true));
        info.setAutoClose(env.getProperty(PREFIX + ".auto_close", Boolean.class, false));
        //  其他
        info.setSoReUseAddr(env.getProperty(PREFIX + ".so_reuseaddr", Boolean.class, false));
        info.setAllowHalfClosure(env.getProperty(PREFIX + ".allow_half_closure", Boolean.class, false));
        info.setWriteSpinCount(env.getProperty(PREFIX + ".write_spin_count", Integer.class, 16));
        return info;
    }

    @Override
    public void parseExpand(Environment env) {
        RpcTcpConfigInfo.INSTANCE = parseTcp(env);
    }
}
